package org.smith.docker.sample.controller;

import org.smith.docker.sample.service.HeapOOMService;
import org.smith.docker.sample.service.HighCPUService;
import org.smith.docker.sample.service.StackOOMService;
import org.smith.docker.sample.service.TestService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class TestController {

    @Resource
    private TestService testService;

    @GetMapping("test")
    public String test(String a) {
        return testService.test(a);
    }

    @Resource
    private HighCPUService highCPUService;

    /**
     * CPU过高测试
     */
    @GetMapping("cpuTest")
    public String cpuTest() {
        highCPUService.cpuTest();
        return "success";
    }

    @Resource
    private HeapOOMService heapOOMService;

    /**
     * 堆内存溢出测试
     */
    @GetMapping("heapOOMTest")
    public String heapOOMTest() {
        heapOOMService.heapOOM();
        return "success";
    }

    @Resource
    private StackOOMService stackOOMService;

    /**
     * 栈溢出测试1
     */
    @GetMapping("stackLeak1")
    public String stackLeak1() {
        try {
            stackOOMService.stackLength = 0;
            stackOOMService.stackLeak1();
        } catch (Throwable e) {
            throw new RuntimeException("stack length: " + stackOOMService.stackLength, e);
        }

        return "success";
    }

    /**
     * 栈溢出测试2
     */
    @GetMapping("stackLeak2")
    public String stackLeak2() {
        try {
            stackOOMService.stackLength = 0;
            stackOOMService.stackLeak2();
        } catch (Throwable e) {
            throw new RuntimeException("stack length: " + stackOOMService.stackLength, e);
        }

        return "success";
    }

    /**
     * 栈溢出测试3
     */
    @GetMapping("newThread")
    public String newThread() {
        try {
            stackOOMService.newThread();
        } catch (Throwable e) {
            System.out.println("创建的线程数：" + stackOOMService.integer.get());
            e.printStackTrace();
            System.exit(1);
        }

        return "success";
    }

}
